package ar.com.ironsoft.javaopenauth.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

/**
 * Util class to work with Maps.
 * 
 * @author Tomas de Priede
 * @version 0.1.3, 05/04/2011
 * @since 0.1.2-SNAPSHOT
 */
public class MapUtils {

	/**
	 * Returns a new map from a querystring<br />
	 * <br />
	 * String queryString = "key1=value1&key2=value2"<br />
	 * map = queryStringToMap(queryString) <br />
	 * assertEquals(value1,map.get("key1")) <br />
	 * assertEquals(value2,map.get("key2"))<br />
	 * 
	 * @param queryString
	 *            the querystring formatted key=value
	 * @return a map with the http params
	 * @author Tomas de Priede
	 * @version 0.1.3, 05/04/2011
	 * @since 0.1.2-SNAPSHOT
	 * @see ar.com.ironsoft.javaopenauth.utils.ValidatorUtils#validateNullOrEmpty(Object...)
	 */
	public static Map<String, String> queryStringToMap(String queryString) {
		ValidatorUtils.validateNullOrEmpty(queryString);
		Map<String, String> map = null;

		map = new HashMap<String, String>();

		for (String s : StringUtils.split(queryString, "&")) {
			String[] pair = StringUtils.split(s, "=");
			if (pair.length == 2) {
				map.put(pair[0], pair[1]);
			} else {
				throw new IllegalArgumentException("Invalid QueryString");
			}
		}
		return map;
	}

	/**
	 * Returns a new encoded with UTF-8 querystring from a map of strings.<br />
	 * Example: <br />
	 * Map<String,String> map = new HashMap<String,String>();<br />
	 * map.put("key1", "value1");<br />
	 * map.put("key2", "value2");<br />
	 * Assert.assertEquals("key2=value2&key1=value1",response);<br />
	 * 
	 * @param params
	 *            a map with the http params
	 * @return queryString the querystring formatted key=value
	 * @author Tomas de Priede
	 * @version 0.1.3, 05/04/2011
	 * @since 0.1.2-SNAPSHOT
	 */
	public static String mapToQueryStringEncoded(Map<String, String> params) {

		ValidatorUtils.validateNullOrEmpty(params);
		String queryString = "";
		try {
			for (Entry<String, String> e : params.entrySet()) {
				if (StringUtils.isNotEmpty(queryString))
					queryString += "&";
				queryString += e.getKey()
						+ "="
						+ URLEncoder.encode(e.getValue(),
								Constants.ENCODING_UTF_8);
			}
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException("Invalid encoding");
		}
		return queryString;
	}
}
